package com.portal.sso.core.server.impl;

import cn.hutool.core.util.StrUtil;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.model.RequestModel;
import com.portal.sso.core.server.RequestServerHandler;
import com.portal.sso.core.util.CookieTools;
import com.portal.sso.core.util.RequestHeaderTools;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @program: portal-sso
 * @description: 抽取请求模型
 * @author: xuduo
 * @create: 2021-04-17 22:48
 * @Version: 1.0
 **/
public class RequestServerHandlerImpl implements RequestServerHandler {
    @Override
    public RequestModel LoadModel(HttpServletRequest request) {
        RequestModel model = new RequestModel(GetUrl(request),GetTgt(request),GetAppId(request));
        return model;
    }

    @Override
    public String GetAppId(HttpServletRequest request) {
        return   request.getParameter(SsoConfig.SSO_APP_ID);
    }

    @Override
    public String GetTgt(HttpServletRequest request) {
        //获取cookie中的tgt
        Cookie tgt_cookie = CookieTools.findCookieByName(request, SsoConfig.SSO_COOKIE_TGT);

        String tgt = null;
        if(tgt_cookie!=null){
            tgt = tgt_cookie.getValue();

        }
        if (StrUtil.isEmpty(tgt)){
            tgt  = RequestHeaderTools.GetTgt(request);
        }
        if(StrUtil.isEmpty(tgt)){
            tgt = request.getParameter(SsoConfig.SSO_PARAMETER_TGT);
        }

        return tgt;
    }

    @Override
    public String GetUrl(HttpServletRequest request) {
        return   request.getParameter(SsoConfig.SSO_REDIRECT_URL);
    }
}
